package com.tom.service.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONPath;
import com.tom.anno.SysLog;
import com.tom.constant.SystemConstant;
import com.tom.dto.ArticleContentDTO;
import com.tom.dto.BaseArticleDTO;
import com.tom.dto.CMSQueryDTO;
import com.tom.dto.CMSResponse;
import com.tom.entity.Article;
import com.tom.exception.BizException;
import com.tom.exception.CommonError;
import com.tom.service.CMSArticleApi;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * All rights Reserved, Designed By www.tom.com
 *
 * @Author 徐望成
 * @Date 2023/12/18 15:29
 * @PackageName:com.tom.service.api
 * @ClassName: CMSArticleApiServiceImpl
 * @Description: TODO
 * @Copyright: 2019 www.tomonline-inc.com Inc. All rights reserved.
 * 注意：本内容仅限于TOM集团内部传阅，禁止外泄以及用于其他的商业目
 * @Version 1.0
 */
@Component
@Slf4j
public class CMSArticleApiServiceImpl implements CMSArticleApi {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${bw-article.url}")
    private String bwArticleApi;


    @Value("${bw-article.listurl}")
    private String magazineArticleListApi;

    @Value("${bw-article.modify-article-list}")
    private String getArticleList;


    @Override
    public ArticleContentDTO getBWArticleDetail(String siteNo, String DataTab, String articleNo) {
        ArticleContentDTO articleContent;
        HttpRequest httpRequest = null;

        try {
            httpRequest = HttpRequest.post(bwArticleApi);
            httpRequest.timeout(1000 * 60);
            httpRequest
                    .form("SiteNo", siteNo)
                    .form("Type", DataTab)
                    .form("ArticleNo", articleNo)
                    .form("cache", "n");

            log.info("查询文章详情:{} ;文章DataTab=:{}", httpRequest, DataTab);
            HttpResponse response = httpRequest.send();
            String articleBodyText = response.bodyText();
            articleContent = JSON.parseObject(articleBodyText, ArticleContentDTO.class);
        } catch (Exception e) {
            log.error("获取文章详情出错:{}", httpRequest, e);
            throw new BizException(CommonError.CAN_NOT_GET_ARTICLE);
        }
        //判断文章是不是已经录入过,如果录入过放回之前的json文件的保存路径
        if (articleContent.getErrorCode() != 1) {
            log.error("获取不到文章详情");
            throw new BizException(CommonError.CAN_NOT_GET_ARTICLE);
        }
        String magazineIssueNumber = articleContent.getJData().getArticle().getMagazineIssueNumber();
        if ("4".equals(DataTab) && StringUtils.isEmpty(magazineIssueNumber)) {
            log.error(CommonError.JOURNAL_INVALID.getMessage());
            throw new BizException(CommonError.JOURNAL_INVALID);
        }
        String webTitle = articleContent.getJData().getArticle().getWebTitle();
        if (StringUtils.isEmpty(webTitle)) {
            log.error(CommonError.TITLE_INVALID.getMessage());
            throw new BizException(CommonError.TITLE_INVALID);
        }
        String webContent = articleContent.getJData().getArticle().getWebContent();
        if (StringUtils.isEmpty(webContent)) {
            log.error(CommonError.CONTEXT_INVALID.getMessage());
            throw new BizException(CommonError.CONTEXT_INVALID);
        }
        return articleContent;
    }

    @Override
    public List<Article> getMagazineArticleList(String siteNo, String IssueNumber, int start, int end) {
        HttpRequest httpRequestcharge = HttpRequest.post(magazineArticleListApi);
        httpRequestcharge.form("SiteNo", siteNo)//10:商周.Com、 16:IOS-APP、17:Andriod-APP
                .form("Type", "7")//
                .form("ID", IssueNumber)
                .form("Start", start)//开始的RankingNo
                .form("End", end)//结束的RankingNo
                .form("Status", "y")//
                .form("SortType", "3")//3為新到舊，4為舊到新
                .form("cache", "n");//是否从缓存里面取，默认从缓存里面取
        HttpResponse responsecharge = httpRequestcharge.send();
        Object chargeExtract = JSONPath.extract(responsecharge.bodyText(), "$.JData.Data");
        List<Article> articlesList = ((JSONArray) chargeExtract).toJavaList(Article.class);
        int count = (int) JSONPath.extract(responsecharge.bodyText(), "$.JData.TotalCount");
        if (end >= count) {
            log.info("付费期刊号为:{}的文章获取到的总数:{}", IssueNumber, count);
        } else {
            log.info("正在取收费文章期刊号为" + IssueNumber + "的" + start + "-" + end + "end");
        }
        return articlesList;
    }

    @SysLog("获取大网变动文章列表")
    @Override
    public List<BaseArticleDTO> getArticleList(CMSQueryDTO queryDTO) {
        try {
            HttpRequest request = HttpRequest.post(getArticleList);
            request.bodyText(JSON.toJSONString(queryDTO), "application/json");
            HttpResponse response = request.send();
            Object jData = JSONPath.extract(response.bodyText(), "$.JData");
            List<BaseArticleDTO> baseArticleDTOS = ((JSONArray) jData).toJavaList(BaseArticleDTO.class);
            if (baseArticleDTOS != null) {
                return baseArticleDTOS;
            }
        } catch (Exception e) {
            log.error("can not obtain any article info {} exception:{}", queryDTO, e);
        }
        return new ArrayList<>();
    }

}
